package com.powernode.config;

import com.powernode.constant.AuthConstants;
import com.powernode.handler.LoginFailureHandler;
import com.powernode.handler.LoginSuccessHandler;
import com.powernode.handler.LogoutSuccessfulHandler;
import com.powernode.service.impl.UserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;

import javax.annotation.Resource;

/**
 * @description:
 * @author: mky
 * @date: 2024/7/5 8:15
 * @version: 1.0
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private UserDetailServiceImpl userDetailService;

    @Autowired
    private LoginSuccessHandler loginSuccessHandler;
    @Autowired
    private LoginFailureHandler loginFailureHandler;
    @Autowired
    private LogoutSuccessfulHandler logoutSuccessfulHandler;
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.cors().disable();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.authorizeHttpRequests()
                .anyRequest()
                .authenticated();

        http.formLogin()
                .loginProcessingUrl(AuthConstants.DOLOGIN)
                .successHandler(loginSuccessHandler)
                .failureHandler(loginFailureHandler);
        http.logout()
                .logoutUrl(AuthConstants.DOLOGOUT)
                .logoutSuccessHandler(logoutSuccessfulHandler);
    }
}
